package com.example.demo;

import com.example.demo.constant.FileAddressConstant;
import com.example.demo.until.FileCloseTimeOption;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.scheduling.annotation.EnableScheduling;

import java.io.File;

@SpringBootApplication
@EnableScheduling
public class MainApp extends Application {
    private ConfigurableApplicationContext springContext;
    private Parent root;

    @Override
    public void init() throws Exception {
        // 解析命令行参数，设置 server.port
        String[] args = getParameters().getRaw().toArray(new String[0]);
        for (String arg : args) {
            if (arg.startsWith("--server.port=")) {
                String port = arg.substring("--server.port=".length());
                System.setProperty("server.port", port); // 设置 Spring Boot 端口
            }
        }

        // 启动 Spring Boot 应用
        springContext = SpringApplication.run(MainApp.class, args);

        // 加载 FXML 文件并设置控制器
        FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/fxml/main.fxml"));
        fxmlLoader.setControllerFactory(springContext::getBean);
        root = fxmlLoader.load();
    }

    @Override
    public void start(Stage primaryStage) throws Exception {
        primaryStage.setScene(new Scene(root, 800, 600));
        primaryStage.setTitle("EverythingDamo");
        primaryStage.show();
    }

    @Override
    public void stop() throws Exception {
        FileCloseTimeOption.saveCloseTimeToFile(new File(FileAddressConstant.OPEN_DATE_TIME_FILE));
        springContext.stop(); // 关闭 Spring 上下文
    }

    public static void main(String[] args) {
        launch(args); // 启动 JavaFX 应用
    }
}